package org.geektimes.config.microprofile;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

import java.util.Iterator;
import java.util.Objects;
import java.util.ServiceLoader;

/**
 * @FileName: DefaultConfigProviderResolver
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/17 - 下午10:06
 */
public class DefaultConfigProviderResolver extends ConfigProviderResolver {

    @Override
    public Config getConfig() {
        return getConfig(null);
    }

    @Override
    public Config getConfig(ClassLoader classLoader) {
        if (Objects.isNull(classLoader)) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        // 通过SPI的方式加载Config对象,取第一个
        ServiceLoader<Config> configs = ServiceLoader.load(Config.class, classLoader);
        Iterator<Config> iterator = configs.iterator();
        return iterator.hasNext() ? iterator.next() : null;
    }

    @Override
    public ConfigBuilder getBuilder() {
        return newConfigBuilder(null);
    }

    protected ConfigBuilder newConfigBuilder(ClassLoader classLoader) {
        return new DefaultConfigBuilder(resolveClassLoader(classLoader));
    }

    protected Config newConfig(ClassLoader classLoader) {
        return newConfigBuilder(classLoader).build();
    }

    private ClassLoader resolveClassLoader(ClassLoader classLoader) {
        return classLoader == null ? this.getClass().getClassLoader() : classLoader;
    }

    @Override
    public void registerConfig(Config config, ClassLoader classLoader) {

    }

    @Override
    public void releaseConfig(Config config) {

    }

}
